//
//  WeatherInfoViewController.m
//  We365
//
//  Created by Pham Khuong Duy on 10/21/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "WeatherInfoViewController.h"
#import "SBJson.h"
#import "Utilities.h"
#import "Settings.h"

@implementation WeatherInfoViewController
@synthesize headerImageView;
@synthesize todayLabel;
@synthesize tomorrowLabel;
@synthesize latitude;
@synthesize longitude;
@synthesize today;
@synthesize tomorrow;
@synthesize conn;
@synthesize webData;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{    
    [super viewDidLoad];
    
    [self getWeather];
    
    [NSTimer scheduledTimerWithTimeInterval:numberOfSeconds target:self selector:@selector(getWeather) userInfo:nil repeats:YES];    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
    [headerImageView release];
    [todayLabel release];
    [tomorrowLabel release];
    [conn release];
    [webData release];
    [super dealloc];
}

- (void)getWeather
{
    if(latitude == 0 && longitude == 0)
        return;
    //view template : http://api.wunderground.com/api/f921ca4d5e255947/conditions/forecast/q/10.800129,106.667703.json
    
    NSString *urlString = [NSString stringWithFormat:@"http://api.wunderground.com/api/f921ca4d5e255947/conditions/forecast/q/%f,%f.json", latitude, longitude];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    conn = [NSURLConnection connectionWithRequest:request delegate:self];   
}

//fusion three images
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 andImage:(UIImage *)image3{
    UIGraphicsBeginImageContext(image1.size);
    
    // Draw image1
    [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
    
    // Draw image2
    [image2 drawInRect:CGRectMake(10, 15, 32, 32)];
    
    // Draw image3
    [image3 drawInRect:CGRectMake(210, 15, 32, 32)];
    
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultingImage;
}

//show result
- (void)showResult:(BOOL)isError
{
    UIImage *headerImage = [self addImage:[UIImage imageNamed:BGWeather] toImage:[UIImage imageNamed:today.icon]  andImage:[UIImage imageNamed:tomorrow.icon]];
    headerImageView.image = headerImage;
            
    NSString *measureKind = [[Settings getAllSettings] objectForKey:kMeasureKind];
    NSString *tempKind = ([measureKind isEqualToString:kKmC] ? @"°C" : @"°F");
    
    if(!isError && [measureKind isEqualToString:kKmC])
    {
        today.currentTemp = [Utilities convertFtoC:today.currentTemp];
        today.highTemp = [Utilities convertFtoC:today.highTemp];
        today.lowTemp = [Utilities convertFtoC:today.lowTemp];
        
        tomorrow.currentTemp = [Utilities convertFtoC:tomorrow.currentTemp];
        tomorrow.highTemp = [Utilities convertFtoC:tomorrow.highTemp];
        tomorrow.lowTemp = [Utilities convertFtoC:tomorrow.lowTemp];
    }
    
    todayLabel.text = [NSString stringWithFormat:@"\r%d%@\rL:%d-H:%d", today.currentTemp, tempKind, today.lowTemp, today.highTemp]; 
    tomorrowLabel.text = [NSString stringWithFormat:@"\r%d%@\rL:%d-H:%d", tomorrow.currentTemp, tempKind, tomorrow.lowTemp, tomorrow.highTemp];
}

//NSURLConnection delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if(!webData)
        webData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [webData release];
    webData = nil;
    
    today.highTemp = today.lowTemp = today.currentTemp = 0;
    today.icon = @"error";
    tomorrow.highTemp = tomorrow.lowTemp = tomorrow.currentTemp = 0;
    tomorrow.icon = @"error";    
    
    [self showResult:YES];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responseString = [[[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding] autorelease];
    
    NSDictionary *root = [responseString JSONValue];    
    NSDictionary *current_observation = [root objectForKey:@"current_observation"];
    
    today.currentTemp = [[current_observation objectForKey:@"temp_f"] intValue];
    today.icon = (NSString *)[current_observation objectForKey:@"icon"];
    
    NSDictionary *simpleforecast = [[root objectForKey:@"forecast"] objectForKey:@"simpleforecast"];
    NSArray *forecastday = [simpleforecast objectForKey:@"forecastday"];
    
    for (int i=0; i<2; i++) {
        NSDictionary *date = [forecastday objectAtIndex:i];
        NSDictionary *high = [date objectForKey:@"high"];
        NSDictionary *low = [date objectForKey:@"low"];
        if (i==0) {
            today.highTemp = [[high objectForKey:@"fahrenheit"] intValue];
            today.lowTemp = [[low objectForKey:@"fahrenheit"] intValue];
        } else {
            tomorrow.highTemp = [[high objectForKey:@"fahrenheit"] intValue];
            tomorrow.lowTemp = [[low objectForKey:@"fahrenheit"] intValue];
            tomorrow.icon = (NSString *)[date objectForKey:@"icon"];
            tomorrow.currentTemp = (tomorrow.highTemp + tomorrow.lowTemp) / 2;
        }
    }
    
    [webData release];
    webData = nil;
    
    [self showResult:NO];
}

@end
